import { defineStore } from "pinia";
import { getQrKey, getQrLogin, getCheck } from "../utils/api";

type UserInfo = {
  avatarUrl?: string;
  code?: number;
  message?: string;
  cookie?: string;
  nickname?: string;
};

interface State {
  userInfo: UserInfo;
  key: string;
  message: string;
}

export const useUserStore = defineStore({
  id: "userStore",
  state: (): State => {
    let storageUserInfo = localStorage.getItem("userInfo");
    return {
      userInfo: storageUserInfo ? JSON.parse(storageUserInfo) : {},
      key: "",
      message: "等待扫码",
    };
  },
  getters: {},
  actions: {
    async actionQrKey() {
      let res: any = await getQrKey();
      this.key = res.data.unikey;
      if (res.code === 200) {
        return await getQrLogin({ key: res.data.unikey, qrimg: "qrimg" });
      }
    },
    async actionCheck() {
      if (this.key) {
        let res: any = await getCheck({ key: this.key });

        this.message = res.message;

        if (res.code === 803) {
          this.userInfo = { ...this.userInfo, ...res };
          localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
          this.message = "登陆成功，即将跳转至首页";
        } else if (res.code === 802) {
          this.userInfo = { ...this.userInfo, ...res };
        }
      }
    },
  },
});
